import Vue from 'vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'
import { getSession, setSession } from '@/utils/session'
import { tbMenuQueryHomeData } from '@/api/admin/system/menu'
import { router, routes, asyncRoute } from '@/router'
import anyRoute from '@/router/anyRoute'
import { deep } from '@/utils/common'
Vue.use(Vuex)

function filterAsyncRouter(menuData) {
  // 过滤第一层路由
  let newRoute = []
  asyncRoute[0].children.forEach((v) => {
    if (!menuData) return
    menuData.forEach((m) => {
      if (m.url.indexOf(v.path) != -1) {
        v.meta.title = m.name
        newRoute.push(v)
      }
    })
  })
  // 过滤第二层路由
  let arrTwo = []
  newRoute.forEach((v) => {
    arrTwo.push(deep({}, v))
  })
  arrTwo.forEach((v) => {
    v.children.splice(0, v.children.length)
  })
  newRoute.forEach((v, idx) => {
    let _childList = menuData.filter(
      (item) => item.url.indexOf(v.path) != -1,
    )[0].childList
    v.children.forEach((m) => {
      _childList.forEach((n) => {
        if (n.url.indexOf(m.path) != -1) {
          m.meta.title = n.name
          arrTwo[idx].children.push(m)
        }
      })
    })
  })
  //新路由如果第一个子路由没有权限重新定位
  arrTwo.forEach((item) => {
    let { children, redirect } = item
    if (children && children.length) {
      let size = redirect.lastIndexOf('/')
      if (size == -1) return
      //后半段
      let behindStr = redirect.substring(size + 1)
      let pathArr = children.map((v) => v.path)
      if (pathArr.indexOf(behindStr) == -1) {
        //前半段
        let frontStr = redirect.substring(0, size)
        let { path } = children[0]
        item.redirect = frontStr + '/' + path
      }
    }
  })

  let newAdminRoute = [
    {
      path: '/admin',
      name: 'admin',
      redirect: '/admin/element-library',
      component: () => import('@/layout/admin/index.vue'),
      children: [...arrTwo],
    },
  ]
  let userType = JSON.parse(getSession('userinfo')).type
  return userType == 1 ? asyncRoute : newAdminRoute
}

const state = {
  menuData: JSON.parse(getSession('webMenu')),
  menuTree: JSON.parse(getSession('menuTree')),
  buttons: getSession('buttons'),
  allRoutes: [],
  asyncRoute: [],
  ifChange: false,
}

const getters = {
  menuData(state) {
    if (!state.menuData) return
    return state.menuData
  },
  submenu(state) {
    if (!state.menuData) return
    return state.menuData[0].childList
  },
  menuTree(state) {
    if (!state.menuTree) return
    return state.menuTree
  },
}

const actions = {
  getTbMenuQueryData({ commit, state }, hebing) {
    return new Promise((resolve, reject) => {
      let webMenu = JSON.parse(getSession('webMenu'))
      if (webMenu) {
        try {
          if (!state.asyncRoute.length && hebing) {
            commit('SETROUTES', filterAsyncRouter(webMenu))
          }
        } catch (error) {
          console.log(error)
        }
        resolve(webMenu)
      } else {
        let userinfo = JSON.parse(getSession('userinfo'))
        if (userinfo) {
          tbMenuQueryHomeData(userinfo.id)
            .then((res) => {
              if (res.data.code == 0) {
                let { menuList, button, menu } = res.data.data[0]
                commit('SETMENUDATA', menuList)
                commit('SETBUTTONS', button)
                if (menuList.length && menuList[0].childList) {
                  commit('SETMENUTREE', menuList[0].childList)
                }
                if (userinfo.id != -1) {
                  menuList.forEach((e) => {
                    if (e.id == 16) {
                      e.childList.forEach((k, index) => {
                        if (k.id == 47) {
                          e.childList.splice(index, 1)
                        }
                      })
                    }
                  })
                }
                commit('SETROUTES', filterAsyncRouter(menuList))
                resolve(webMenu)
              }
            })
            .catch((error) => {
              reject(error)
            })
        }
      }
    })
  },
}

const mutations = {
  SETMENUDATA: (state, d) => {
    setSession('webMenu', JSON.stringify(d))
    state.menuData = d
  },
  SETMENUTREE: (state, d) => {
    setSession('menuTree', JSON.stringify(d))
    state.menuTree = d
  },
  SETBUTTONS: (state, d) => {
    if (!d) return
    setSession('buttons', d)
    state.buttons = d
  },
  SETROUTES: (state, d) => {
    state.asyncRoute = d
    let resultAllroute = routes.concat(d, ...anyRoute)
    state.allRoutes = resultAllroute
    setSession('allRoutes', JSON.stringify(resultAllroute))
    setSession('asyncRoute', JSON.stringify(d))
    router.matcher = new VueRouter({
      routes: resultAllroute,
    }).matcher
    state.ifChange = true
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
